// pages/choice-shop/index.js
import {
  calcDistance
} from "../../utils/util.js"

const app = getApp();

const setting = {
  skew: 0,
  rotate: 0,
  showLocation: true,
  showScale: false,
  subKey: 'TXCBZ-KVB6J-OQ7FV-DFXTG-26BB2-ATFFU',
  layerStyle: 1,
  enableZoom: true,
  enableScroll: true,
  enableRotate: true,
  showCompass: true,
  enable3D: true,
  enableOverlooking: true,
  enableSatellite: false,
  enableTraffic: false,
}

// latitude: 42.839480881130164, longitude: 93.50107103058212
// latitude: 42.833426369429226, longitude: 93.54099202283032
const allMarkers = [{
    id: 2,
    name: app.data.shops.shopsDetails[2].name,
    tag: app.data.shops.shopsDetails[2].tag,
    latitude: 42.833426369429226,
    longitude: 93.54099202283032,
    distance: 0,
    distanceUnit: 'km',
    iconPath: app.data.global_urls.locationIcon,
    callout: {
      content: '昌吉葱花饼店\n（大修厂店）',
      color: '#ff0000',
      fontSize: 14,
      bgColor: 'transparent',
      padding: 0,
      display: 'ALWAYS',
      textAlign: 'center',
      anchorY: 10
    },
  },
  {
    id: 1,
    name: app.data.shops.shopsDetails[1].name,
    tag: app.data.shops.shopsDetails[1].tag,
    latitude: 42.839480881130164,
    longitude: 93.50107103058212,
    distance: 0,
    distanceUnit: 'km',
    iconPath: app.data.global_urls.locationIcon,
    callout: {
      content: '昌吉葱花饼店\n（兴业园店）',
      color: '#ff0000',
      fontSize: 14,
      bgColor: 'transparent',
      padding: 0,
      display: 'ALWAYS',
      textAlign: 'center',
      anchorY: 10
    },
  }
]

Page({

  /**
   * 页面的初始数据
   */
  data: {
    setting: setting,
    latitude: 42.839480881130164,
    longitude: 93.50107103058212,
    myLatitude: 0,
    myLongitude: 0,
    markers: allMarkers,
    shops: '',
    shopSelected: 0,
    intervalId:0,
  },

  _getLocation() {
    var that = this;
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'wgs84',
        success(res) {
          const latitude = res.latitude
          const longitude = res.longitude
          const speed = res.speed
          const accuracy = res.accuracy

          that.setData({
            myLatitude: res.latitude,
            myLongitude: res.longitude
          })
          resolve({
            myLatitude: that.data.myLatitude,
            myLongitude: that.data.myLongitude
          });
        },
        fail(e) {
          console.log('位置获取失败', e);
          reject(e);
        }
      });
    });
  },

  _calcDistance() {
    console.log('计算距离')
    this._getLocation().then(
      ({
        myLatitude,
        myLongitude
      }) => {
        if (myLongitude === 0 || myLatitude === 0) {
          console.error('位置获取失败')
          return;
        }

        // 1. 计算距离
        this.data.markers.forEach((item) => {
          var distance = calcDistance(myLatitude, myLongitude, item.latitude, item.longitude);
          item.distance = distance;
        })

        // 2. 排序，设置最近距离
        this.data.markers.sort((a, b) => a.distance - b.distance);

        // 3. 设置单位
        this.data.markers.forEach((item) => {
          var distance = item.distance;
          if (distance > 1) {
            item.distanceUnit = 'km'
            item.distance = Math.round(distance * 100) / 100;
          } else {
            item.distanceUnit = 'm'
            item.distance = Math.round(distance * 1000);
          }
        })

        // 刷新页面
        this.setData({
          markers: this.data.markers
        })
      }
    ).catch(((e) => {
      console.log(e)
    }));
  },

  moveToMyLocation() {
    this.mapCtx.moveToLocation();
  },

  moveToShop(e) {
    let marker = e.currentTarget.dataset.marker;

    this.setData({
      shopSelected: marker.id
    })

    app.data.shops.index = marker.id;
    this.setData({
      shops: app.data.shops
    })

    this.mapCtx.moveToLocation({
      longitude: marker.longitude,
      latitude: marker.latitude,
    });

    setTimeout(() => {
      wx.navigateBack();
    }, 500)

    // 2. get all goods list
    app.getAllGoodsList();
  },

  getXYAxis(res) {
    console.log(res)
  },

  onBack() {
    wx.navigateBack();
  },
  onGoHome() {
    wx.reLaunch({
      url: '/pages/home/home',
    });
  },

  exploreTo(e) {
    let marker = e.currentTarget.dataset.marker;
    
    console.log('开启导航', e)
    this.mapCtx.openMapApp({
      latitude: marker.latitude,
      longitude: marker.longitude,
      destination: '昌吉葱花饼店',
      success(e) {
        console.log('拉起成功', e)
      },
      fail() {
        console.log('拉起失败', e)
      }
    })
  },

  onShow() {
    this.mapCtx = wx.createMapContext('myMap');
    // 计算距离
    this._calcDistance();
    this.data.intervalId = setInterval(()=>{
      this._calcDistance();
    }, 3000);

    // 刷新页面
    this.setData({
      shops: app.data.shops,
    })

    setTimeout(() => {
      this.mapCtx.includePoints({
        padding: [-200, 100, 0, 100],
        points: [{
          latitude: allMarkers[0].latitude,
          longitude: allMarkers[0].longitude
        }, {
          latitude: allMarkers[1].latitude,
          longitude: allMarkers[1].longitude
        }]
      })
    }, 2000)
  },

  onHide(){
    clearInterval(this.data.intervalId)
  },

  onUnload(){
    clearInterval(this.data.intervalId)
  },

  findItemById(id, arr) {
    console.log('call findItemById')
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].id === id) {
        return arr[i];
      }
    }
    return null;
  }
})